package com.hemaapp.yjnh.activity;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CustomBlogAdapter2;
import com.hemaapp.yjnh.bean.BlogType;
import com.hemaapp.yjnh.bean.CustomBlog;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 通用定制商品列表
 * 带商品分类
 */
public class CmnCustomizeListWithSortActivity extends BaseActivity {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.iv_sort)
    ImageView ivSort;
    @Bind(R.id.tv_sort_name)
    TextView tvSortName;
    @Bind(R.id.layout_sort)
    LinearLayout layoutSort;
    @Bind(R.id.layout_price)
    LinearLayout layoutPrice;
    @Bind(R.id.layout_sales)
    LinearLayout layoutSales;
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout refreshLoadmoreLayout;

    private ArrayList<BlogType> types = new ArrayList<>();
    private ArrayList<CustomBlog> customBlogs = new ArrayList<>();
    private CustomBlogAdapter2 adapter;
    private int page = 0;
    private String typename = "";//分类名称
    private String ordertype = "1";//1:降序；2:升序
    private String orderby = "0";//0时间排序；1价格排序；2销量排序
    private User user;
    private LoginUtil.LoginCallBack loginCallBack;
    private PopupWindow mPopupWindow;
    private String keytype = "3";//类型	1粮库;2农需;3定制;4农货;5单位

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_cmn_production_list_with_sort);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        user = getApplicationContext().getUser();
        EventBus.getDefault().register(this);
        getNetWorker().getBlogTypeList(keytype, "0");
        refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void getExras() {
    }

    @Override
    protected void setListener() {
        titleRightBtn.setVisibility(View.GONE);
        titleText.setText(mIntent.getStringExtra("title"));
        refreshLoadmoreLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().getCustomBlogList("0", "1", typename, "1", orderby, ordertype, page + "");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().getCustomBlogList("0", "1", typename, "1", orderby, ordertype, page + "");
            }
        });
    }

    @OnClick({R.id.title_left_btn, R.id.layout_sort, R.id.layout_price, R.id.layout_sales})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.layout_sort:
                if (mPopupWindow == null)
                    initPopuptWindow();
                mPopupWindow.showAsDropDown(layoutSort);
                break;
            case R.id.layout_price:
                if (orderby.equals("1")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else
                        ordertype = "1";
                } else {
                    layoutPrice.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutSort.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "1";
                    ordertype = "1";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
            case R.id.layout_sales:
                if (orderby.equals("2")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else
                        ordertype = "1";
                } else {
                    layoutSales.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSort.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "2";
                    ordertype = "1";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOGTYPE_LIST:
            case CUSTOM_BLOG_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOGTYPE_LIST:
            case CUSTOM_BLOG_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_LIST:
                HemaPageArrayResult<CustomBlog> iResult = (HemaPageArrayResult<CustomBlog>) baseResult;
                if (iResult == null || iResult.getObjects() == null)
                    return;
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    if (iResult.getObjects().size() == 0)
                        refreshLoadmoreLayout.setLoadmoreable(false);
                    else
                        refreshLoadmoreLayout.setLoadmoreable(true);
                    customBlogs.clear();
                    customBlogs.addAll(iResult.getObjects());
                } else {// 更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    customBlogs.addAll(iResult.getObjects());
                    if (iResult.getObjects().size() > 0) {
                        customBlogs.addAll(iResult.getObjects());
                    } else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshData(-1);
                break;
            case BLOGTYPE_LIST:
                HemaArrayResult<BlogType> typeResult = (HemaArrayResult<BlogType>) baseResult;
                if (typeResult == null || typeResult.getObjects() == null)
                    return;
                types.clear();
                BlogType allType = new BlogType();
                allType.setName("全部分类");
                types.add(allType);
                types.addAll(typeResult.getObjects());
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOGTYPE_LIST:
                XtomToastUtil.showShortToast(mContext, "获取分类失败," + baseResult.getMsg());
                break;
            case CUSTOM_BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOGTYPE_LIST:
                XtomToastUtil.showShortToast(mContext, "获取分类失败,请稍后再试");
                break;
            case CUSTOM_BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                refreshData(failedType);
                break;
        }
    }

    private void refreshData(int failedType) {
        if (null == adapter) {
            adapter = new CustomBlogAdapter2(mContext, customBlogs);
            adapter.setEmptyString("暂无商品");
            listview.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setFailtype(failedType);
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }
    }

    private void initPopuptWindow() {
        final View popView = getLayoutInflater().inflate(R.layout.pop_blog_assort, null);
        final ListView listView = (ListView) popView.findViewById(R.id.listview);
        int width = layoutSort.getWidth();
        listView.getLayoutParams().width = width;
        listView.setAdapter(new AssortAdapter());

        mPopupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        popView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int top = listView.getTop();
                int wide = listView.getRight();
                int bottom = listView.getBottom();
                int y = (int) event.getY();
                int x = (int) event.getX();
                if (x > wide || y < top || y > bottom) {
                    mPopupWindow.dismiss();
                }
                return true;
            }
        });
    }

    class AssortAdapter extends android.widget.BaseAdapter {

        public AssortAdapter() {

        }

        @Override
        public int getCount() {
            return types.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_pop_blog_assort, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(R.id.TAG_VIEWHOLDER, holder);
            }else
                holder = (ViewHolder) convertView.getTag(R.id.TAG_VIEWHOLDER);
            holder.setData(position);
            return convertView;
        }

        class ViewHolder {
            @Bind(R.id.iv_assort)
            ImageView ivAssort;
            @Bind(R.id.tv_assort)
            TextView tvAssort;
            int position;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        tvSortName.setText(types.get(position).getName());
                        ImageUtils.loadAssortWhite(mContext, types.get(position).getImgurl(), ivSort);
                        if (position == 0)
                            typename = "";
                        else
                            typename = types.get(position).getName();
                        orderby = "0";
                        ordertype = "1";
                        refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                        layoutSort.setBackgroundColor(Color.parseColor("#ffae40"));
                        layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                        layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    }
                });
            }

            private void setData(int position) {
                this.position = position;
                ImageUtils.loadAssort(mContext, types.get(position).getImgurl(), ivAssort);
                tvAssort.setText(types.get(position).getName());
            }
        }
    }
}
